package com.leff.cards.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.leff.cards.data.AppState;
import com.leff.cards.web.QueryDispatcher;
import com.leff.notifications.NotificationCenter;
import com.leff.notifications.NotificationListener;

public abstract class BaseActivity extends SherlockFragmentActivity implements NotificationListener {
	
	private NotifReceiver mReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if(mReceiver == null) {
			mReceiver = new NotifReceiver();
		}
		this.registerReceiver(mReceiver, mReceiver.getFilter());

		NotificationCenter.registerListener(this, QueryDispatcher.QUERY_BEGAN);
		NotificationCenter.registerListener(this, QueryDispatcher.QUERY_FINISHED);
		NotificationCenter.registerListener(this, QueryDispatcher.QUERY_ERROR);
	}

	@Override
	protected void onPause() {
		super.onPause();
		
		if(mReceiver != null) {
			this.unregisterReceiver(mReceiver);
		}
		
		NotificationCenter.unregisterListener(this, QueryDispatcher.QUERY_BEGAN);
		NotificationCenter.unregisterListener(this, QueryDispatcher.QUERY_FINISHED);
		NotificationCenter.unregisterListener(this, QueryDispatcher.QUERY_ERROR);
	}
	
	@Override
	public void onNotificationPosted(String name, Object data, Object sender) {
		
		if(QueryDispatcher.QUERY_BEGAN.equals(name)) {
			this.setSupportProgressBarIndeterminateVisibility(true);
		}
		else if(QueryDispatcher.QUERY_FINISHED.equals(name)) {
			this.setSupportProgressBarIndeterminateVisibility(false);
		}
		else if(QueryDispatcher.QUERY_ERROR.equals(name)) {
			String message = (String)data;
			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
		}
	}
	
	private class NotifReceiver extends BroadcastReceiver {
		
		public IntentFilter getFilter() {
			IntentFilter IF = new IntentFilter();
			IF.addAction("com.google.android.c2dm.intent.RECEIVE");
			
			return IF;
		}

		@Override
		public void onReceive(Context C, Intent I) {
			AppState.get().refreshAll();
			this.abortBroadcast();
		}
	}
}
